package com.test.reactor.control;

import java.time.Duration;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.test.reactor.ws.SocketSessionRegistry;

import reactor.core.publisher.Flux;
import reactor.util.function.Tuples;

/**
 * 服务器推送事件（Server-Sent Events，SSE）允许服务器端不断地推送数据到客户端
 * 
 * SSE 在浏览器端的支持也比较广泛，除了 IE 之外的其他浏览器都提供了支持。在 IE 上也可以使用 polyfill 库来提供支持。
 */
@RestController
@RequestMapping("/sse")
public class SseController {
	@Autowired
    private SocketSessionRegistry sessionRegistry;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/randomNumbers")
    public Flux<ServerSentEvent<String>> randomNumbers() {
         Flux<ServerSentEvent<String>> map = Flux.interval(Duration.ofSeconds(10))
                .map(seq -> Tuples.of(seq, getUserJsonArray()))
                .map(data -> ServerSentEvent.<String>builder()
                        .event("random")
                        .id(Long.toString(data.getT1()))
                        .data(data.getT2())
                        .build());
         return map;
    }

	private String getUserJsonArray() {
        Object user = redisTemplate.opsForHash().keys("user").stream().map(o -> o.toString().replace("userAddress:us-", "")).collect(Collectors.toSet());
        return JSONArray.toJSON(user).toString();
	}
}